import { showWxToast } from '../../../utils/index';
import { withDrawHbyMoney } from '../../../api/recharge/recharge';

Page({
  data: {
    hbyRemainMoney: 0,
    withdrawMoney: '',
    isAgree: false,
    isWithdrawAll: false,
  },
  onLoad: function(options) {
    this.setData({
      hbyRemainMoney: options.hbyRemainMoney,
    });
  },
  onShow: function() {},
  onUnload: function() {},
  toWithdrawRecord: function() {
    wx.navigateTo({
      url: '/pages/userCenter/withdrawRecord/withdrawRecord',
    });
  },
  toggleAgree: function() {
    let tmpIsAgree = this.data.isAgree;
    tmpIsAgree = !tmpIsAgree;
    this.setData({
      isAgree: tmpIsAgree,
    });
  },
  toggleWithdrawAll: function() {
    let tmpIsWithdrawAll = this.data.isWithdrawAll;
    tmpIsWithdrawAll = !tmpIsWithdrawAll;
    this.setData({
      isWithdrawAll: tmpIsWithdrawAll,
    });
    if (this.data.isWithdrawAll) {
      this.setData({
        withdrawMoney: this.data.hbyRemainMoney,
      });
    }
  },
  toAgreement: function() {
    wx.navigateTo({
      url: '/pages/agreement/agreement',
    });
  },
  handleMoneyInput: function(e) {
    let tmpMoneyStr = e.detail.value;
    let r = /^\+?[1-9][0-9]*$/; //正整数
    let flag = r.test(tmpMoneyStr);
    if (flag || tmpMoneyStr === '0.01') {
      // 只能是正整数或者是0.01
      this.setData({
        money: tmpMoneyStr,
      });
    } else {
      this.setData({
        money: '',
      });
    }
  },
  handleWithdrawMoney: function() {
    if (!this.data.isAgree) {
      showWxToast('请先同意服务条款!');
      return;
    }
    if (this.data.hbyRemainMoney === '0') {
      showWxToast('余额为0!');
      return;
    }
    if (parseFloat(this.data.hbyRemainMoney) < 1) {
      showWxToast('高于1元方能提现!');
      return;
    }
    withDrawHbyMoney()
      .then(res => {
        console.log(res);
        if (res.flag === '3') {
          this.setData({
            hbyRemainMoney: 0,
          });
          showWxToast('提现成功!');
        } else {
          showWxToast(res.msg);
        }
      })
      .catch(err => {
        console.log(err);
        showWxToast('提现失败!');
      });
  },
});
